package com.zust513.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zust513.dto.RegionPressureDTO;
import com.zust513.entity.Region;
import com.zust513.mapper.RegionMapper;
import com.zust513.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 区域服务实现类
 */
@Service
public class RegionServiceImpl implements RegionService {

    @Autowired
    private RegionMapper regionMapper;

    @Override
    public List<RegionPressureDTO> getAllRegionPressure() {
        List<Region> regions = regionMapper.findAllRegions();
        List<RegionPressureDTO> result = new ArrayList<>();

        for (Region region : regions) {
            result.add(convertToDTO(region));
        }

        return result;
    }

    @Override
    public RegionPressureDTO getRegionPressureById(Integer regionId) {
        Region region = regionMapper.findRegionById(regionId);
        if (region == null) {
            return null;
        }
        return convertToDTO(region);
    }

    /**
     * 将Region实体转换为RegionPressureDTO
     */
    private RegionPressureDTO convertToDTO(Region region) {
        RegionPressureDTO dto = new RegionPressureDTO();
        dto.setRegionId(region.getRegionId());
        dto.setName(region.getName());
        dto.setPressureLevel(region.getPressureLevel());

        // 获取该区域的配送员数量
        Integer courierCount = regionMapper.countCouriersByRegionId(region.getRegionId());
        dto.setCourierCount(courierCount);

        // 获取该区域的订单数量
        Integer orderCount = regionMapper.countOrdersByRegionId(region.getRegionId());
        dto.setOrderCount(orderCount);


        return dto;
    }
}
